<template>
  <d2-container class="page">
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>

    <el-dialog
      width="1024px"
      :title="createOrEdit"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" ref="form">
        <el-form-item label="供应商" :label-width="formLabelWidth">
          <el-select v-model="form.supplierCode" filterable placeholder="请选择">
            <el-option
              v-for="item in supplierList"
              :key="item.id"
              :label="item.supplierName"
              :value="item.supplierCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" :label-width="formLabelWidth">
          <el-select v-model="form.categoryId" filterable placeholder="请选择">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="退换货规则" :label-width="formLabelWidth">
          <el-select v-model="form.returnRuleId" filterable placeholder="请选择">
            <el-option
              v-for="item in aftersaleConfList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="运费模板" :label-width="formLabelWidth">
          <el-select v-model="form.freightTemplateId" filterable placeholder="请选择">
            <el-option
              v-for="item in freightList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.spuName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图片(spu只能1张图)" :label-width="formLabelWidth">
          <el-upload
            action="https://xcx.ruiysoft.com/reserve/qiniu/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :limit="1"
            :on-success="handleUploadSuccess"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示顺序" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.sequence" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品详情图(html)" :label-width="formLabelWidth">
          <el-input v-model="form.info" :rows="5" placeholder="请输入内容" type="textarea"></el-input>
          <el-button
            type="success"
            size="mini"
            @click="jump2Url('https://www.365editor.com/')"
          >html编辑器</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="createOrEdit=='新建'" type="primary" @click="handleCreateNew('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>
    <el-button type="primary" size="mini" @click="showCreateDlg('form')">新建</el-button>&nbsp;
    <el-select v-model="supplierCode" filterable placeholder="请选择供应商" size="mini">
      <el-option v-for="item in supplierList" :key="item.id" :label="item.supplierName" :value="item.supplierCode"></el-option>
    </el-select>&nbsp;
    <el-select v-model="categoryId" filterable placeholder="请选择分类" size="mini">
      <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
    </el-select>&nbsp;
    <el-button type="primary" size="mini" @click="getList()">搜索</el-button>
    <el-button type="danger" size="mini" @click="clearCache()">清除缓存</el-button>
    <el-divider></el-divider>
    <el-table
      stripe
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%;"
      v-loading="loading"
    >
      <!-- <el-table-column type="selection" width="55"></el-table-column> -->
      <!-- <el-table-column label="id" width="120">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>-->
      <el-table-column type="index" label="序号"></el-table-column>

      <el-table-column label="SPU">
        <template slot-scope="scope">{{ scope.row.spuId }}</template>
      </el-table-column>
      
      <el-table-column label="供应商" width="200">
        <template slot-scope="scope">{{ scope.row.supplierName }}</template>
      </el-table-column>
      <el-table-column label="分类">
        <template slot-scope="scope">{{ scope.row.category }}</template>
      </el-table-column>
      <el-table-column label="名称" width="250">
        <template slot-scope="scope">{{ scope.row.spuName }}</template>
      </el-table-column>
      <el-table-column label="图片" width="100">
        <template slot-scope="scope">
          <img v-bind:src="scope.row.photo" style="width:100%" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="运费模板">
        <template slot-scope="scope">{{ scope.row.freightName }}</template>
      </el-table-column> -->
      <el-table-column label="显示顺序">
        <template slot-scope="scope">{{ scope.row.sequence}}</template>
      </el-table-column>
      <el-table-column label="市场价" width="150">
        <template slot-scope="scope">{{ scope.row.listPrice }}</template>
      </el-table-column>
      <el-table-column label="销售价" width="150">
        <template slot-scope="scope">{{ scope.row.unitPrice }}</template>
      </el-table-column>
      <el-table-column label="库存" width="150">
        <template slot-scope="scope">{{ scope.row.quantity }}</template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">{{ scope.row.status | upOrDown }}</template>
      </el-table-column>
      
      <el-table-column align="center" label="操作" width="200px" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showEditDlg(scope.row)">编辑SPU</el-button>
          <el-button size="mini" type="success" @click="showStandardList(scope.row)">编辑SKU</el-button>
          <div style="height:5px"/>
          <el-button size="mini" @click="upOrDownSpu(1, scope.row.spuId)">上架</el-button>
          <el-button size="mini" @click="upOrDownSpu(2, scope.row.spuId)">下架</el-button>
          <div style="height:5px"/>
          <el-button size="mini" type="primary" @click="comment(scope.row)">评论</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            icon="el-icon-delete"
          ></el-button>
          
        </template>
      </el-table-column>
    </el-table>
    <br />
    <el-pagination background layout="prev, pager, next" :total="50"></el-pagination>
  </d2-container>
</template>

<script>
import * as goods from "@/api/shop.goods";
import * as supplier from "@/api/shop.supplier";
import { rejects } from "assert";
import * as freight from "@/api/shop.freight";

export default {
  name: "goods",
  components: {},
  data() {
    return {
      supplierCode: null,
      categoryId: null,
      loading: true,
      fileList: [],
      tableData: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {},
      formLabelWidth: "200px",
      dialogImageUrl: "",
      dialogVisible: false,
      createOrEdit: "",
      downloadPath: "",
      listQuery: {
        pageStart: 1,
        pageSize: 25
      },
      categoryList: null,
      aftersaleConfList: null,
      dialogStandardVisible: false,
      supplierList: null,
      freightList: null
    };
  },
  mounted() {
    this.getList();
    this.$route.meta.title = "商品管理";
  },
  created() {
    goods.getCategoryList({ pageStart: 1, pageSize: 25 }).then(resp => {
      console.log(resp);
      this.categoryList = resp.data.list;
    });

    goods.getAftersaleConfList({ pageStart: 1, pageSize: 25 }).then(resp => {
      console.log(resp);
      this.aftersaleConfList = [];
      resp.data.forEach(element => {
        element.name =
          "退货, " + element.returnedDay + "; 换货, " + element.exchangeDay;
        this.aftersaleConfList.push(element);
      });
    });

    supplier.fetchList().then(resp => {
      this.supplierList = resp.data.records;
    });

    freight
        .fetchList({ queryCondition: JSON.stringify(this.listQuery) })
        .then(response => {
          if (response.success) this.freightList = response.data;
        });


  },
  filters: {
    upOrDown: function(val) {
      if (val == 1) return "上架";
      if (val == 2) return "下架";
    }
  },
  methods: {
    clearCache() {
      goods.clearCache().then(resp => {
        console.log(resp);
        if (resp.success) {
          this.$notify({
            title: "提示",
            message: "清除缓存成功，清除后第一访问的人会创建缓存所以有点慢。后面访问的人都会直接访问缓存，就会快起来。",
            type: "success",
            duration: 5000
          });
        }
      });
    },

    comment(row) {
      this.$router.push({
        path: "/shop/goods/commentList",
        query: { spuId: row.spuId, spuName: row.spuName }
      });
    },

    jump2Url(url) {
      window.open(url, "_blank");
    },

    showStandardList(row) {
      // this.dialogStandardVisible = true;

      // goods.spuDetailById(row.spuId).then(resp => {
      //   console.log(resp);
      //   this.$router.push({
      //     path: "/shop/goods/skuList",
      //     query: { list: resp.data.skus }
      //   });
      // });

      this.$router.push({
        path: "/shop/goods/skuList",
        query: {
          spuId: row.spuId,
          spuName: row.spuName,
          categoryId: row.categoryId
        }
      });
    },

    upOrDownSpu(upOrDown, spuId) {
      let ids = [];
      ids.push(spuId);
      goods.upOrDownSpu(upOrDown, ids).then(resp => {
        console.log(resp);
        if (resp.success) {
          this.getList();
          this.$notify({
            title: "提示",
            message: "创建成功",
            type: "success",
            duration: 2000
          });
        }
      });
    },

    search() {
      this.getList();
    },

    showCreateDlg(formName) {
      this.dialogFormVisible = true;
      this.createOrEdit = "新建";
      // this.$refs[formName].resetFields();
      this.form = {};
      this.fileList = [];
    },

    showEditDlg(row) {
      this.dialogFormVisible = true;
      this.createOrEdit = "编辑";

      goods.spuDetailById(row.spuId).then(resp => {
        console.log(resp);
        this.form = resp.data;

        // 赋值后不能编辑 ?
        if(row.sequence != undefined)
          this.form.sequence = row.sequence;

        this.fileList = [{ url: resp.data.photos[0].photoUrl }];

        // 退换货规则
        goods.querySpuTuihhgz(row.spuId).then(resp => {
          if (resp.success) {
            this.form.returnRuleId = resp.data.id;
          }
        });
      });
    },

    handleUploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.success)
        this.fileList.push({
          url: response.downloadPath,
          photoUrl: response.downloadPath,
          sort: 0,
          type: 1,
          delFlag: 0
        });
    },

    handleCreateNew(formName) {
      let that = this;

      const set = that.$refs;
      set[formName].validate(valid => {
        if (valid) {
          that.form.photos = that.fileList;
          that.form.type = 1;
          that.form.status = 1;
          that.form.RuleValues = [
            { id: -1, delFlag: 0, ruleName: "默认规格", value: "默认规格值" }
          ];
          that.form.skus = [
            {
              ruleName: "默认规格",
              value: "默认规格值",
              listPrice: "0",
              unitPrice: "0",
              quantity: "0",
              memberPrice: null,
              integral: null,
              RuleValues: [
                {
                  delFlag: 0,
                  ruleName: "默认规格",
                  value: "默认规格值"
                }
              ],
              name: "默认规格 请删除",
              photos: [
                {
                  photoUrl:
                    "http://media.avicyt.com/%E5%8D%A0%E4%BD%8D%E5%9B%BE%E7%89%87.png",
                  sort: 0,
                  type: 1
                }
              ],
              photoUrl:
                "http://media.avicyt.com/%E5%8D%A0%E4%BD%8D%E5%9B%BE%E7%89%87.png",
              delFlag: 0
            }
          ];

          goods.createOrEdit(that.form).then(resp => {
            if (resp.success) {
              that.dialogFormVisible = false;
              that.getList();
              that.$notify({
                title: "提示",
                message: "创建成功",
                type: "success",
                duration: 2000
              });
            } else {
              that.$notify({
                title: "提示",
                message: "异常: " + resp.bizMessage,
                type: "error",
                duration: 2000
              });
            }
          });
        } else {
          return false;
        }
      });
    },

    update(formName) {
      let that = this;

      const set = that.$refs;
      set[formName].validate(valid => {
        if (valid) {
          that.form.merchandiseName = that.form.spuName;
          that.form.mainCategory = that.form.categoryId;
          that.form.spuPicture = that.fileList[0].url;

          goods.updateSpu(that.form).then(resp => {
            if (resp.success) {
              // 退换货规则
              goods
                .setSpuTuihhgz(that.form.returnRuleId, [that.form.spuId])
                .then(resp => {
                  if (resp.success) {
                    that.$notify({
                      title: "提示",
                      message: "创建成功",
                      type: "success",
                      duration: 2000
                    });
                  }
                });

              that.dialogFormVisible = false;
              that.getList();
            } else {
              that.$notify({
                title: "提示",
                message: "异常: " + resp.bizMessage,
                type: "error",
                duration: 2000
              });
            }
          });
        } else {
          return false;
        }
      });
    },

    getList() {
      this.loading = true;
      this.listQuery.categoryId = this.categoryId;
      goods.fetchList(this.listQuery).then(response => {
        this.loading = false;
        if (response.success) this.tableData = response.data.list;
      });
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
      const index = this.fileList.indexOf(file, 0);
      if (index > -1) {
        this.fileList.splice(index, 1);
      }
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleDelete(row) {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        goods
          .deleteById(row.spuId)
          .then(() => {
            this.getList();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
          })
          .catch(() => {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "error",
              duration: 2000
            });
          });
      });
    }
  }
};
</script>